import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserPermission,
  LoginData,
  getUserInfo,
} from '@/api/login';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

const clearCache = () => {
  localStorage.removeItem('form1');
  localStorage.removeItem('form2');
  localStorage.removeItem('form3');
};

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    staffId: undefined,
    branchId: undefined,
    deptId: undefined,
    deptName: undefined,
    staffPhone: undefined,
    createTime: undefined,
    permissions: [],
    staffName: undefined,
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    setPermissions(permissions: string[]) {
      this.permissions = permissions;
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async getPermission() {
      const data = await getUserPermission();
      this.setPermissions(data.map((e: any) => e.code));
    },

    async getInfo() {
      const data = await getUserInfo();
      this.setInfo(data);
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        // console.log(res);
        setToken(res.accessToken);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        clearCache();
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
